package com.test.demo;

import java.net.DatagramSocket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myprojectoffeixue.R;
import com.macrovideo.animate.RadarView;
import com.macrovideo.sdk.custom.DeviceInfo;
import com.macrovideo.sdk.smartlink.SmarkLinkTool;
import com.macrovideo.sdk.tools.DeviceScanner;
import com.macrovideo.sdk.tools.Functions;



/**
 * ����������
 * @author Administrator
 *
 */
public class SmartLinkQuickWifiConfigActivity extends Activity implements OnClickListener, OnItemClickListener {
	
	////WIFI
	private WiFiAdnim mWiFiAdnim;  
	private WifiManager mWiFiManager;   //����һ��WifiManager
	private WifiReceiver mwReceiver;   //����һ��WifiReceiver
	private android.net.wifi.WifiInfo mWifiInfo;    //����һ��wifiInfo
	private List<ScanResult> locaWifiDeiviceList = new ArrayList<ScanResult>();
	////
	
	private LinearLayout lLayoutWifiInputPage; //��ʾ������׼�����ã���ʼ����
	private ImageView btnSLBack, ivSLPwdVisible; //���ذ�ť����ʼ�����ð�ť����ʵ����wifi���밴ť
	private Button btnSLSearchBack=null;
	private Button btnSLStartConfig; //��һ��;
	private EditText etSLWifiSSID, etSLWifiPassword;  //wifi��ƣ�wifi����
	
	private View soundWaveConfigConctentView=null;//, soundWaveConfigDemoState = null;  //���ڼ���listView��View
	private Dialog soundWaveConfigDialog = null;//, soundWaveConfigDemoStateDialog = null; // ������ʵListView��DiaLog
	private ImageView ivSoundWaveConfigWifiListViewBack; //wifi��?�ذ�ť
	private ListView lvSoundWaveConfigWifi;  //�����õ�wifi�б�
	
 	
	private ProgressDialog progressDialog; //����ȷ��wifi�б��Ƿ����?
	private boolean bWifiPassword = true;  //�����ж��Ƿ���������
	
 	
	private LinearLayout llayoutSLSearchingPage; // ��ʾ������׼�����ã���ʼ����
 	private FrameLayout flayoutSLSearchingAnimate; //��ʾ��������
 	private RadarView searchAminatView;
	private String strConnSSID;  //��ǰ�ֻ����ӵ�wifi�û���
	private MediaPlayer soundPlayer = null;// ��������
	private MediaPlayer soundPlayerHint = null;  //
	
 	
 	
	private static final int WIFI_CONNECT = 0x11;
	private static final int WIFI_CONNECT2 = 0x12;
	private static final int WIFI_NOT_CONNECT = 0x14;
	private static final int SEEK_DEVICE_OVERTIME = 0x13;
	private boolean bWifiOpen = false;
  	private AlertDialog.Builder wifiNoticeDialog = null;
 	private boolean bIsNoticeShow = false; //
 	private boolean bIsConfiging = false; //
	
 	private int nTimeoutDetectID = 0; 
	
 	private TextView tvTimeLeft = null;
  
 	private ArrayList<DeviceInfo> deviceList = null;
 	private int nConfigID = 0;
 	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		 requestWindowFeature(Window.FEATURE_NO_TITLE);//���ر���  ��  
		setContentView(R.layout.activity_smartlink_wifi_config);
		initView(); //��ʼ������ؼ�?
		 
	 
	}

	
	
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
		initWifi(); //��ʼ��wifi ���� ������wifi�㲥
		wifiChooseWindow(); //��ʼ����ʵwifi�б��Dialog
		
//		new ThreadWifilist().start();
	}


	@Override
	public void onStop(){
		
		try{
			if(soundPlayerHint !=null)
			{
				soundPlayerHint.stop(); //�ر���ʾ��
			}
			
			if(soundPlayer != null)
			{
				soundPlayer.stop(); //�ر�����
			}
		}catch(Exception e){
			
		}
		if(bIsConfiging){
		
			SmarkLinkTool.StopSmartConnection(); // ֹͣ����smarkLin
			showInputPage();
			bIsConfiging=false;
		}
		
	 
		super.onStop();
	}


	@Override
	protected void onDestroy() {

		
		soundPlayer = null;// ��������
		soundPlayerHint = null;  //
		 
		locaWifiDeiviceList = null;
		mWifiInfo = null;
		

		BitmapDrawable llayoutSLSearchingBG = (BitmapDrawable) flayoutSLSearchingAnimate.getBackground();
		flayoutSLSearchingAnimate.setBackgroundResource(0);
		if(llayoutSLSearchingBG!=null){
			llayoutSLSearchingBG.setCallback(null);
			llayoutSLSearchingBG.getBitmap().recycle();
			System.gc();
		}
		super.onDestroy();
		
		
		
	}




	/**
	 * ��ʼ���ؼ�
	 */
	@SuppressWarnings("deprecation")
	private void initView()
	{
		
		lLayoutWifiInputPage = (LinearLayout) findViewById(R.id.lLayoutWifiInputPage);
 		
		btnSLBack = (ImageView) findViewById(R.id.btnSLBack);
		btnSLBack.setOnClickListener(this);
 
		ivSLPwdVisible = (ImageView) findViewById(R.id.ivSLPwdVisible);
		ivSLPwdVisible.setOnClickListener(this);
		
		btnSLStartConfig = (Button) findViewById(R.id.btnSLStartConfig);
		btnSLStartConfig.setOnClickListener(this);
		
		etSLWifiSSID = (EditText) findViewById(R.id.etSLWifiSSID);
		etSLWifiSSID.setOnClickListener(this);
		etSLWifiPassword = (EditText) findViewById(R.id.etSLWifiPassword);
		
		lLayoutWifiInputPage.setVisibility(View.VISIBLE);
 		etSLWifiPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); // Ĭ����ʾ����
 
 		llayoutSLSearchingPage =  (LinearLayout) findViewById(R.id.llayoutSLSearchingPage);
		flayoutSLSearchingAnimate = (FrameLayout) findViewById(R.id.flayoutSLSearchingAnimate);
		flayoutSLSearchingAnimate.setBackgroundDrawable(new BitmapDrawable(Functions.readBitMap(this, R.drawable.radar_bg)));
		llayoutSLSearchingPage.setVisibility(View.GONE);
		
  
		btnSLSearchBack = (Button) findViewById(R.id.btnSLSearchBack);
		btnSLSearchBack.setOnClickListener(this);
		// gifͼ
		searchAminatView = (RadarView) findViewById(R.id.searchAminatView);
		searchAminatView.setWillNotDraw(false); //
//		searchAminatView.startAnimate();
//		
		tvTimeLeft =(TextView) findViewById(R.id.tvTimeLeft);
 	}
	
	
	
	//��Ϣ��ʾ��
  	public void ShowAlert(String title, String msg){
	  		
  			new AlertDialog.Builder(this)//
  			.setTitle(title).setMessage(msg)
  			.setPositiveButton(getString(R.string.alert_btn_OK), new DialogInterface.OnClickListener() {

  			public void onClick(DialogInterface dialog, int whichButton) {

  				setResult(Activity.RESULT_OK);
  			}

  			}).show();

  	}
	/**
	 * ��ʼ��wifi
	 */
	private void initWifi()
	{
		 mWiFiAdnim = new WiFiAdnim(this);
		 mWiFiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
		 mWifiInfo = mWiFiManager.getConnectionInfo();
		 
		 //����ֻ�������wifi ��
		 if(mWiFiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED && mWifiInfo != null)
		 { //���wifi�Ǵ�״̬
			 strConnSSID = mWifiInfo.getSSID();
//			 System.out.println("GetSSID= "+strConnSSID+", "+strConnSSID.equalsIgnoreCase("0x"));//
 
			 if(strConnSSID != null && strConnSSID.length() > 0 && !strConnSSID.equalsIgnoreCase("0x"))
			 {
//				 System.out.println("GetSSID= "+strConnSSID.substring(0, 1)+", "+strConnSSID.substring(strConnSSID.length()-1, strConnSSID.length()));//add for test
				 
				 if(strConnSSID.substring(0, 1).equals("\"") && strConnSSID.substring(strConnSSID.length()-1, strConnSSID.length()).equals("\"") ){
					 strConnSSID = strConnSSID.substring(1, (strConnSSID.length()-1));  //�õ���ǰ���ӵ��û���ȥ��ǰ��˫���?
				 }
				 
				 etSLWifiSSID.setText(strConnSSID);
			 }else{
				 etSLWifiSSID.setText("");
			 }
//			 btnSLStartConfig.setEnabled(true);
			 if(lLayoutWifiInputPage.getVisibility() == View.VISIBLE)
				{
					if(!isLanguage())
					{
						soundPlayerHint = MediaPlayer.create(this, R.raw.input_wifi_pwd);
						soundPlayerHint.setLooping(false);
						soundPlayerHint.start();
					}
				}

			 
		 }else{ //wifiû�п���
			 if(!bIsNoticeShow){
				 wifiNoticeDialog= new AlertDialog.Builder(this);
				 
				 wifiNoticeDialog.setTitle(getString(R.string.wifiConnect));
				 wifiNoticeDialog.setMessage(getString(R.string.wifi_start_bt));
				 wifiNoticeDialog.setPositiveButton(getString(R.string.wifi_is),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									mWiFiAdnim.openWifi(); // ����wifi
									bIsNoticeShow = false;
									progressDialog = new ProgressDialog(SmartLinkQuickWifiConfigActivity.this);
									progressDialog
										.setProgressStyle(ProgressDialog.STYLE_SPINNER);
									progressDialog.setCanceledOnTouchOutside(false);
									progressDialog.setMessage(getString(R.string.wifi_start));
									progressDialog.show(); // ��ʾ�����?
									
								}
							});
				 wifiNoticeDialog.setNegativeButton(getString(R.string.wifi_no),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									bIsNoticeShow = false;
								}
							});
				 wifiNoticeDialog.show();
				 bIsNoticeShow = true;
			 }
			
			 
		 }
		 ///ע��wifi�㲥������
		 mwReceiver = new WifiReceiver(); 
	     registerReceiver(mwReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
	     ////
	     mWiFiAdnim.startScan();  //��ʼɨ������
	     
	   
	}
	
	// �ж�wifi�Ƿ��Ǵ򿪵�
		public boolean isWiFiActive() {
			ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				@SuppressWarnings("deprecation")
				NetworkInfo[] infos = connectivity.getAllNetworkInfo();
				if (infos != null) {
					for (NetworkInfo ni : infos) {
						if (ni.getTypeName().equals("WIFI") && ni.isConnected()) {
							return true;
						}
					}
				}
			}
			return false;
		}


	/**
	 * wifiѡ�񴰿�
	 */
	private void wifiChooseWindow()
	{
		soundWaveConfigConctentView= LayoutInflater.from(getApplication()).inflate(R.layout.sound_wave_config_window, null);
		soundWaveConfigDialog= new Dialog(this,R.style.dialog_bg_transparent);  
		soundWaveConfigDialog.setContentView(soundWaveConfigConctentView);
		soundWaveConfigDialog.setOnShowListener(new OnShowListener(){

 			@Override
 			public void onShow(DialogInterface dialog) {
 				// TODO Auto-generated method stub
 				onSoundWaveConfigListViewDialogShow();
 			}
 			
 		});
	}
	
	/**
	 * ��ʾwifi�б�
	 */
	private void onSoundWaveConfigListViewDialogShow()
	{
		
		ivSoundWaveConfigWifiListViewBack = (ImageView) soundWaveConfigConctentView.findViewById(R.id.ivSoundWaveConfigBack);
		lvSoundWaveConfigWifi = (ListView) soundWaveConfigConctentView.findViewById(R.id.lvSoundWaveConfig);
		lvSoundWaveConfigWifi.setCacheColorHint(Color.TRANSPARENT);
		ivSoundWaveConfigWifiListViewBack.setOnClickListener(this);
		lvSoundWaveConfigWifi.setOnItemClickListener(this);
		
		//listView��ݼ��ز����?
		if(locaWifiDeiviceList != null && locaWifiDeiviceList.size() > 0)
		{
			DeviceSoundWaveConfigAdapter deviceSoundWaveConfigAdapter = new DeviceSoundWaveConfigAdapter(SmartLinkQuickWifiConfigActivity.this, locaWifiDeiviceList, R.layout.time_zone_item,
					   new String[]{"item_list"} , new int[]{R.id.tvTimeZone});
			   if(lvSoundWaveConfigWifi != null)
			   {
				   lvSoundWaveConfigWifi.setAdapter(deviceSoundWaveConfigAdapter); //
			   }else{
				   lvSoundWaveConfigWifi = (ListView) soundWaveConfigConctentView.findViewById(R.id.lvSoundWaveConfig);
				   lvSoundWaveConfigWifi.setAdapter(deviceSoundWaveConfigAdapter); //
			   }
		}
		
		   
	}
	
	
	
	
	
	/**
	 * �жϵ�ǰ����
	 * @return
	 */
	public boolean isLanguage()
	{
		boolean bisLanguage = false;
		
		String locale = Locale.getDefault().getLanguage();
		if(locale.equals("en"))  //�����Ӣ��?
		{
			bisLanguage = true;
		}
		return bisLanguage;
	}
	
	
	//�б�
	public class DeviceSoundWaveConfigAdapter extends BaseAdapter{

		   private class ItemViewHolder{
			   TextView tvTimeZone;
		   }
		   
		   private List <ScanResult> mAppList; 
	       private LayoutInflater mInflater; 
	       private Context mContext; 
	       private String [] keyString; 
	       private int [] valueViewID; 
	       private ItemViewHolder holder; 
	       
	       public DeviceSoundWaveConfigAdapter(Context c,List<ScanResult> appList, int resource, 
	                 String [] from , int [] to)
	       {
	    	   	 mAppList = appList; 
	             mContext = c; 
	             mInflater = (LayoutInflater) mContext. getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	             
	             keyString = new String [from.length] ; 
	             valueViewID = new int [to.length] ; 
	       }
		   
		@Override
		public int getCount() {
			
			return mAppList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mAppList.get(position);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			  if (convertView != null) { 
	                 holder = (ItemViewHolder)convertView.getTag() ; 
	             } else { 
	                 convertView = mInflater.inflate(R.layout.time_zone_item, null); 
	                 holder = new ItemViewHolder() ; 
	                 holder.tvTimeZone = (TextView) convertView.findViewById(R.id.tvTimeZone);
	                 convertView.setTag(holder) ; 
	             }
			 
			  if(mAppList != null && mAppList.size() > 0)
			  {
				  holder.tvTimeZone.setText(mAppList.get(position).SSID);
			  }else{
				//  holder.tvTimeZone.setText("");  
			  }
			  
			 
			
			return convertView;
		}
		   
	   }
	
	 /**
	  * �����жϵ�ǰ�����Ƿ�ʱ
	  * @author Administrator
	  *
	  */
	 public class TimeoutDetectThread extends Thread{

		 private int nThreadID = 0;
		public TimeoutDetectThread(int nThreadID){
			this.nThreadID = nThreadID;
		}
		 
		@Override
		public void run() {
			
			int nCount = 83;
			while(nTimeoutDetectID==nThreadID){
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					 
				}
				nCount--;
				if(nCount<=0){
					break;
				}
			} 
			
			if(nThreadID == nTimeoutDetectID )
			{ // 
				
				 Message msg = handler.obtainMessage();
				 msg.arg1 = SEEK_DEVICE_OVERTIME;
				 handler.sendMessage(msg);
			}
			
		}

	 }
	 
	
	 private void showInputPage(){
		 
		 lLayoutWifiInputPage.setVisibility(View.VISIBLE);
		 llayoutSLSearchingPage.setVisibility(View.GONE);
	 }

	 private void showSearchingPage(){
		 lLayoutWifiInputPage.setVisibility(View.GONE);
		 llayoutSLSearchingPage.setVisibility(View.VISIBLE);
	 }
	@Override
	public void onClick(View arg0) {
		
		switch (arg0.getId()) {
		case R.id.btnSLSearchBack: //������ذ��?
			searchAminatView.stopAnimate();
			try{
				if(!isLanguage() && soundPlayerHint !=null)
				{
					soundPlayerHint.stop(); //�ر���ʾ��
				}
				
				if(soundPlayer != null)
				{
					soundPlayer.stop(); //�ر�����
				}
			}catch(Exception e){
				
			}
			
			bIsConfiging=false;
			SmarkLinkTool.StopSmartConnection(); // ֹͣ����smarkLin
			showInputPage();
			nTimeoutDetectID++; 
			
			
			break;
		case R.id.btnSLBack: //������ذ��?
			

			bIsConfiging=false;
			SmarkLinkTool.StopSmartConnection(); // ֹͣ����smarkLin
			
			try{
				if(!isLanguage() && soundPlayerHint !=null)
				{
					soundPlayerHint.stop(); //�ر���ʾ��
				}
				
				if(soundPlayer != null)
				{
					soundPlayer.stop(); //�ر�����
				}
			}catch(Exception e){
				
			}
			 
 			this.unregisterReceiver(mwReceiver);
			Intent intent = new Intent(SmartLinkQuickWifiConfigActivity.this, DeviceListViewActivity.class);
			startActivity(intent);
			
			SmartLinkQuickWifiConfigActivity.this.finish();
			 
			break;
		 
		case R.id.btnSLStartConfig: //�����һ�����?
			
			//���¼�������
			
			if(!isLanguage())
			{	if(soundPlayerHint !=null)
				{
					soundPlayerHint.stop();
				}
				
				soundPlayerHint = MediaPlayer.create(this, R.raw.device_perpare);
				soundPlayerHint.setLooping(false);
				soundPlayerHint.start();
			}
			
			String strSSID = etSLWifiSSID.getText()+"";
			String strPassword = etSLWifiPassword.getText()+"";
			nConfigID= LocalDefines.getConfigID();
			bIsConfiging=true;
 
 
//		
			SmarkLinkTool.StartSmartConnection(nConfigID, strSSID, strPassword); //��ʼ����smarkLink
			
			searchAminatView.startAnimate();
			showSearchingPage();
			
 			StartSearchDevice(); //��ʼ�����豸��
			if(!isLanguage() && soundPlayerHint !=null)
			{
				soundPlayerHint.stop();  //�ر�����
			}
			soundPlayer = MediaPlayer.create(this, R.raw.seekmusic); //��������
			soundPlayer.setLooping(true);
			soundPlayer.start();
			
			tvTimeLeft.setText(""+80);
			nTimeoutDetectID++;
			
			 CountDownTimer timer = new CountDownTimer(80000, 1000) {  
				    int nThreadID = nTimeoutDetectID;
				    int nCount = 80;
			        @Override  
			        public void onTick(long millisUntilFinished) {  
			        	if(nThreadID != nTimeoutDetectID){
			       
			        		return;
			        	}
			        	if (tvTimeLeft != null) {  
			            	nCount--;
			            	if(nCount<0)nCount=0;
			            	try{
			            		tvTimeLeft.setText(""+nCount); 
			            	}catch(Exception e){
			            		
			            	}
			                 
			            }    
			        }  
			  
			        @Override  
			        public void onFinish() {  
			        	if(nThreadID == nTimeoutDetectID )
						{ // 
							
							 Message msg = handler.obtainMessage();
							 msg.arg1 = SEEK_DEVICE_OVERTIME;
							 handler.sendMessage(msg);
						}
			        }  
			    };  
			    timer.start();
			break;
			
		case R.id.etSLWifiSSID: //�����wifi����ı���?
			
			//����wifiѡ�񴰿�
		
			soundWaveConfigDialog.show();
			
			
			break;
		case R.id.ivSoundWaveConfigBack:  //wifi��?�ڷ��ذ�ť
			
			if(soundWaveConfigDialog != null)
			{
				soundWaveConfigDialog.dismiss();
			}
			
			break;
			
		case R.id.ivSLPwdVisible:  //�������ʾ�������밴�?
			
			if(bWifiPassword)
			{
				bWifiPassword = false;
				etSLWifiPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
				ivSLPwdVisible.setImageResource(R.drawable.netword_hide);
				Editable etable = etSLWifiPassword.getText();
				Selection.setSelection(etable, etable.length());
			}else{
				
				bWifiPassword = true;
				etSLWifiPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
				ivSLPwdVisible.setImageResource(R.drawable.netword_show_password);
				Editable etable = etSLWifiPassword.getText();
				Selection.setSelection(etable, etable.length());
			}
			
			break;
		
	 
	 
		default:
			break;
		}
		
	}
	
 
	
	
	
	/**
	 * listView����¼�?
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
		//wifi�б����¼�
		
		lvSoundWaveConfigWifi.setSelection(arg2);
		
		if(locaWifiDeiviceList != null && locaWifiDeiviceList.size()>0)
		{
			String WifiSSID = locaWifiDeiviceList.get(arg2).SSID;
			if(WifiSSID != null && WifiSSID.length()>0)
			{
				etSLWifiSSID.setText(WifiSSID);
				etSLWifiPassword.setText("");
				Editable etable = etSLWifiSSID.getText();
				Selection.setSelection(etable, etable.length());
				if(soundWaveConfigDialog != null)
				{
					soundWaveConfigDialog.dismiss();
				}
			}
			
			//wifi�ļ�������
			String wifiCapabilities  = locaWifiDeiviceList.get(arg2).capabilities;
			if(wifiCapabilities != null && wifiCapabilities.length() > 0)
			{
 			}
		}
		
		
	}
	
	
	/**
	  * ����һ���ڲ���  ���й㲥ɨ��������ȵ����?
	  * @author Administrator
	  *
	  */
	 public class WifiReceiver extends BroadcastReceiver 
	 {
		public void onReceive(Context c, Intent intent) 
	     {

	    	// locaWifiDeiviceList.clear();
	    	 locaWifiDeiviceList = mWiFiManager.getScanResults();  //��������ȵ����?
	    	 
	    	 
	    	//����źŵ�ǿ�ȶ�locaWifiDeiviceList��������
	    	if (!locaWifiDeiviceList.isEmpty()) 
	    	{
	    		Collections.sort(locaWifiDeiviceList, new Comparator<ScanResult>() 
	    		{
	    		     @Override
	    			 public int compare(ScanResult object1,
	    				        ScanResult object2) 
	   				 {
	    				      int i = Math.abs(object1.level)+""
	    				                    .compareTo( Math.abs(object2.level)+"");
	    				      return i;
	    			 }
	    		});
	    	} 
	    				
	    	if(locaWifiDeiviceList != null && locaWifiDeiviceList.size() > 0 && progressDialog != null)
	    	{
	    			progressDialog.dismiss();	
	    			bWifiOpen = true;
	    	}
	    }	
	     
	 }
	 
	 /**
	  * ��������
	  * @param capabilities
	  * @return
	  */
	 private int wifiEncrye(String capabilities)
	 {
		 int encrye = 1;
		 
		 if( capabilities.indexOf("WPA2") != -1)
 		 {
			 encrye = 3;
 		 }else if(capabilities.indexOf("[WPA-PSK-TKIP+CCMP]") != -1
 				 || capabilities.indexOf("[WPA2-PSK-TKIP+CCMP]") != -1)
 		 {
 			encrye = 3;
 		 }else if(capabilities.indexOf("[WEP]") != -1
 				 && capabilities.indexOf("[IBSS]") != -1)
 		 {
 			encrye = 2;
 		 
 		 }else if(capabilities.indexOf("[WEP]") != -1)
 		 {
 			encrye = 2;
 			 
 		 }else if(capabilities.indexOf("[WPA-PSK-CCMP]") != -1
 				 || capabilities.indexOf("[WPA-PSK-TKIP+CCMP]") != -1)
 		 {
 			 
 			encrye = 3;
 			 
 		 }else if(capabilities.indexOf("[WPA2-PSK-CCMP]") != -1
 				 || capabilities.indexOf("[WPA2-PSK-TKIP+CCMP]") != -1)
 		 {
 			encrye = 3;
 			 
 		 }else if( capabilities.indexOf("[ESS]") != -1)
 		 {
 			encrye = 1;
 		 }
 		 
		 
		 return encrye;
	 }
	 
	 
	 
	 
	 @Override
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
			//����Ƿ��ؼ�?ֱ�ӷ��ص�����
			if(keyCode == KeyEvent.KEYCODE_BACK ){

				bIsConfiging=false;
				SmarkLinkTool.StopSmartConnection(); // ֹͣ����smarkLin
				try{
					if(soundPlayerHint !=null)
					{
						soundPlayerHint.stop(); //�ر���ʾ��
					}
					
					if(soundPlayer != null)
					{
						soundPlayer.stop(); //�ر�����
					}
				}catch(Exception e){
					
				}
				
				
			   if(lLayoutWifiInputPage.getVisibility() == View.VISIBLE){
 					Intent intent = new Intent(this, DeviceListViewActivity.class);
					startActivity(intent);
					finish();
					
				}else if(llayoutSLSearchingPage.getVisibility() == View.VISIBLE)
				{
					SmarkLinkTool.StopSmartConnection(); // ֹͣ����smarkLin
					showInputPage();
 					StopSearchDevice();
				}
			}
			return false;
	 	}
	 
	 
	 
	/////////////////////////////////////add by luo 20150407
	private Handler handler = new Handler() {
			@SuppressLint("HandlerLeak")
			public void handleMessage(Message msg) {

				if(msg.arg1 == WIFI_CONNECT2)
				{
					if(!bWifiOpen)
					{
						if(progressDialog != null)
						{  //���wifi�б�ûˢ�³���
							progressDialog.dismiss();
							Toast.makeText(SmartLinkQuickWifiConfigActivity.this, getString(R.string.wifiListingFail), Toast.LENGTH_SHORT).show();
						}
					}
					
					
				}
				
				//�豸������ʱ
				if(msg.arg1 == SEEK_DEVICE_OVERTIME)
				{
					//��ʱ����
					nTimeoutDetectID++;
					searchAminatView.stopAnimate();
					try{
						if(!isLanguage() && soundPlayerHint !=null)
						{
							soundPlayerHint.stop(); //
						}
						
						if(soundPlayer != null)
						{
							soundPlayer.stop(); //
						}
					}catch(Exception e){
						
					}
					
					bIsConfiging=false;
					SmarkLinkTool.StopSmartConnection(); // ֹͣ����smarkLin
					showInputPage();
					
					ShowAlert(getString(R.string.snartLinkFailTitle), getString(R.string.snartLinkFailHint));

				}
				
				//wifi���ӳɹ�
				if(msg.arg1 == WIFI_CONNECT)
				{
					if(progressDialog != null)
					{
						progressDialog.dismiss();
					}
				}
				
				//wifi����ʧ��
				if(msg.arg1 == WIFI_NOT_CONNECT)
				{
					if(progressDialog != null)
					{
						progressDialog.dismiss();
					}
					
					Toast.makeText(SmartLinkQuickWifiConfigActivity.this, getString(R.string.connect_wifi_off), Toast.LENGTH_SHORT).show();
				}
				
				//�����豸�ɹ�
				if (msg.arg1 == LocalDefines.DEVICE_SEARCH_RESULT) {
					nTimeoutDetectID++;
					bIsConfiging=false;
				//	IoTManagerNative.StopSmartConnection();
					SmarkLinkTool.StopSmartConnection(); // ֹͣ����smarkLin
						StopSearchDevice();
						DeviceInfo info = null;
						switch (msg.arg2) {
						case LocalDefines.DEVICE_SEARCH_RESULT_OK:

							if (deviceList != null && deviceList.size() > 0) {
								// //@@System.out.println("DEVICE_SEARCH_RESULT");//add for
								// test
								boolean bNewDevFound = false;
								String searchResultMsg = getString(R.string.add_device);

								for (int i = 0; i < deviceList.size(); i++) {
									info = (DeviceInfo) deviceList.get(i);
									if (info != null) {

										if (!DatabaseManager.IsInfoExist(info)) {

											if (DatabaseManager.AddServerInfo(info)) {
												
												bNewDevFound = true;
												if (i == 0) {
													searchResultMsg = searchResultMsg
															+ info.getStrName();
												} else {
													searchResultMsg = searchResultMsg
															+ ", " + info.getStrName();
												}
											}
										} else {// ����豸�Ѵ��ڣ������һ��ip��ַ�Ͷ˿���Ϣ
											// //@@System.out.println("DEVICE_SEARCH_RESULT �豸�Ѵ���");//add
										// for test
											if (DatabaseManager.UpdateServerInfo(info)) {
												bNewDevFound = true;
											}

										}
									}

								}
								if (deviceList.size() > 0) {

									if (bNewDevFound) {
										
										//add by luo 20150714
										LocalDefines.reloadDeviceInfoList();
										LocalDefines.isDeviceListSet=false;
										LocalDefines.nClientDeviceSettingThreadID++;
							        
							            //end add by luo 20150714
							            
										//�ɹ��������豸
							            nTimeoutDetectID++;
										if(soundPlayer != null)
										{
											soundPlayer.stop();
										}
										
										lLayoutWifiInputPage.setVisibility(View.VISIBLE);
										llayoutSLSearchingPage.setVisibility(View.GONE);
										StopSearchDevice();  //ֹͣ�����豸��
										Intent intent = new Intent(SmartLinkQuickWifiConfigActivity.this, DeviceListViewActivity.class);
										startActivity(intent);
										
										finish();
										

									} else {
										Toast toast = Toast.makeText(
												SmartLinkQuickWifiConfigActivity.this,
												getString(R.string.search_finish),
												Toast.LENGTH_SHORT);
										toast.setGravity(Gravity.CENTER, 0, 0);
										toast.show();
										
										StartSearchDevice();  //��ʼ�����豸��
									}

								} else {
									Toast toast = Toast.makeText(
											SmartLinkQuickWifiConfigActivity.this,
											getString(R.string.no_dev_found),
											Toast.LENGTH_SHORT);
									toast.setGravity(Gravity.CENTER, 0, 0);
									toast.show();
									StartSearchDevice();  //��ʼ�����豸��
								}

							} else {
								Toast toast = Toast.makeText(
										SmartLinkQuickWifiConfigActivity.this,
										getString(R.string.no_dev_found),
										Toast.LENGTH_SHORT);
								toast.setGravity(Gravity.CENTER, 0, 0);
								toast.show();
								StartSearchDevice();  //��ʼ�����豸��
							}

							break;
						case LocalDefines.DEVICE_SEARCH_RESULT_FAIL:
							
//							// searchTitle.setText(getString(R.string.has)+" 0 "+getString(R.string.device_found));
							Toast toast = Toast.makeText(
									SmartLinkQuickWifiConfigActivity.this,
									getString(R.string.no_dev_found),
									Toast.LENGTH_SHORT);
							toast.setGravity(Gravity.CENTER, 0, 0);
							toast.show();
							break;

						}

					}

			}

		}; 
		
 
 

//////////add by mai 2015-4-10  ���������豸\
	 
	private int m_nSearchID = 0;//
	private boolean bIsSearching = false;
	private boolean mIsSearchingMode = false; 
	DatagramSocket ipuStationudpSocket = null;
	DatagramSocket ipuAPudpSocket = null;
		// ��ʼ�豸����
	public boolean StartSearchDevice() {
			

			try {
				if (!Functions.isNetworkAvailable(this
						.getApplicationContext())) {// ���粻����
				//	connectingDialog.dismiss();
					Toast toast = Toast.makeText(
							this.getApplicationContext(),
							getString(R.string.toast_network_unreachable),
							Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					return false;
				}
			} catch (Exception e) {
				return false;
			}
			m_nSearchID++;
			bIsSearching = true;

//			((HomePageActivity) relateAtivity).closeMulticast();
//			((HomePageActivity) relateAtivity).openMulticast();
			new BroadCastUdp(m_nSearchID).start();
			return true;

		}
		
		

		// ֹͣ�豸����
	public void StopSearchDevice() {
			
			bIsSearching = false;
			m_nSearchID++;
			mIsSearchingMode = false;
		}

		// �豸�����߳�
		public class BroadCastUdp extends Thread {

			private int nTreadSearchID = 0;

			public BroadCastUdp(int nSearchID) {
				nTreadSearchID = nSearchID;
		
			}

			public void run() {

				while (bIsSearching && nTreadSearchID == m_nSearchID) {
					
					
					deviceList = DeviceScanner.getDeviceListFromLan(nConfigID);
					
					if(deviceList != null && deviceList.size() > 0){
						
						Message msg = handler.obtainMessage();
						msg.arg1 = LocalDefines.DEVICE_SEARCH_RESULT;
						msg.arg2 = LocalDefines.DEVICE_SEARCH_RESULT_OK;
						handler.sendMessage(msg);
					 }
 
					
				}

			}

		}
	 
	 ////end add by mai 2015-4-10
	 

}
